import { ref, onMounted, onUnmounted } from 'vue'

export function useTableHeight(offset = 280, containerSelector = '.el-card') {
    const tableHeight = ref(500)

    const updateTableHeight = () => {
        try {
            // 获取浏览器窗口高度
            const windowHeight = window.innerHeight

            // 尝试获取容器元素的高度信息
            const container = document.querySelector(containerSelector)
            let containerOffset = 0

            if (container) {
                const rect = container.getBoundingClientRect()
                containerOffset = rect.top + 30 // 30是额外的边距
            }

            // 计算表格高度（减去顶部和其他元素的高度）
            tableHeight.value = windowHeight - containerOffset - offset

            // 确保表格高度不会太小
            if (tableHeight.value < 300) {
                tableHeight.value = 300
            }
        } catch (error) {
            // 如果计算出错，使用默认值
            tableHeight.value = 500
            console.warn('计算表格高度时出错:', error)
        }
    }

    // 在组件中使用时需要调用的生命周期钩子
    const mountTableHeight = () => {
        updateTableHeight()
        window.addEventListener('resize', updateTableHeight)
    }

    const unmountTableHeight = () => {
        window.removeEventListener('resize', updateTableHeight)
    }

    return {
        tableHeight,
        updateTableHeight,
        mountTableHeight,
        unmountTableHeight
    }
}